import { getWeather } from '@/servers';
import { ref, reactive, watch } from 'vue';

const cache = {};
const useWeather = () => {
  const state = reactive({
    city: '',
    future: [],
    realtime: {}
  });
  function changeCity(newCity) {
    newCity = newCity.trim();
    if (cache[newCity]) {
      state.city = cache[newCity].city;
      state.future = cache[newCity].future;
      state.realtime = cache[newCity].realtime;
      return;
    }
    getWeather(newCity).then(data => {
      cache[newCity] = {};
      cache[newCity].city = state.city = data.city;
      cache[newCity].future = state.future = data.future.map(item => {
        item.date = item.date.substr(5);
        return item;
      });
      cache[newCity].realtime = state.realtime = data.realtime;
    });
  }
  changeCity('北京'); // 初始化
  return {
    state,
    changeCity
  };
};
export { useWeather };
